// ==UserScript==
// @name			Ikariam Online Status Collector
// @namespace		Ikariam-Online-Status-Collector
// @description		Collects online status from Ikariam through embassy 
// @author			salomone
// @version			0.1.2
// @include			http://s*.ikariam.*/*view=embassy*
// ==/UserScript==
// History:
// v.0.1.0 - 16/06/2010
//	* first commited
//	* base functionality, rdy to test
// v.0.1.1 - 20/06/2010
//	* senderPlayerName is used to transfer in a third parameter
//	* new (a second one), simplier submitter function
// v.0.1.2 - 21/06/2010
//	* fixed elkuld() function

$ = document.getElementById;
var gameServer = top.location.host;
var url = self.location.href;

var memberListTable = null; 

var trimEverythingExceptNumbers = new RegExp('[\\D]', 'g');

// Ha ezt bekapcsolod, akkor (elvileg) elküldi az adatokat. Nem teszteltem, kellene két funkció:
// - Egy táblázat ami id - név - időbélyeg oszlopokból áll
// - Egy gomb, ami törli a tábla tartalmát
var submitMode = false;

var globalSorterIdx = 2; 

// Ha ezt bekapcsolod, akkor csak az első 10 embert szedi össze
var shortenedList = false;


function getGM_Value( variableName )	{
	return GM_getValue ( variableName );
}

function setGM_Value ( variableName, variableValue )	{
	GM_setValue ( variableName, variableValue );
}

if ( url.indexOf('view=embassy') > 0  )	{		
	memberListTable = getMemberListTable();	
	putButton();
}

function addEvent(obj, evType, fn, bubble)	{
	if (obj.addEventListener)	{
		obj.addEventListener(evType, fn, bubble);
		return true;
	} 
	else if (obj.attachEvent)	{
		var r = obj.attachEvent('on'+evType, fn);
		return r;
	}
	else	{
		return false;
	}
}

function $x( xpath, root ) {
  var doc = root ? root.evaluate ? root : root.ownerDocument : document, next;
  var got = doc.evaluate( xpath, root||doc, null, 0, null ), result = [];
  switch (got.resultType) {
    case got.STRING_TYPE:
      return got.stringValue;
    case got.NUMBER_TYPE:
      return got.numberValue;
    case got.BOOLEAN_TYPE:
      return got.booleanValue;
    default:
      while (next = got.iterateNext())
        result.push( next );
      return result;
  }
}

function $X( xpath, root ) {
	  var got = $x( xpath, root );
	  return got instanceof Array ? got[0] : got;
}

function getMemberListTable()	{
	var mainView = $X(".//div[@id='mainview']");
	var contentDiv = $x("./div[@class='contentBox01h']", mainView)[1];	
	return $X("./div[@class='content']/table[@id='memberList']", contentDiv);
	
}

function getMemberListRows(memberListTable)	{	
	return $x("./tbody/tr/td[@class='online']/..", memberListTable);
}

function getMemberNameFromRow(memberListRow)	{
	return $X("./td[position() = 2 ]", memberListRow).firstChild.nodeValue;
}

function getMemberIdFromRow(memberListRow)	{	
	var idCell = $X("./td[@class='action']", memberListRow);	
	var linkElement = $X("./div/div/a", idCell);
	
	if ( linkElement == 'undefined' || linkElement == null )	{
		return null;
	}
	
	var hrefStr = linkElement.getAttribute('href');	
	var receiverStr = hrefStr.split("receiverId")[1];
	return receiverStr.split("=")[1];
	
}

function getContextBoxRoot(page)	{
	if (page)	{
		return $X(".//div[@id='mainview']/div[@class='contentBox01h']", page);
	}
	
	return $X(".//div[@id='mainview']/div[@class='contentBox01h']");
}

function putButton()	{	
	var startButton = null;
	startButton = document.createElement('input');
	startButton.setAttribute('type', 'button');
	startButton.setAttribute('id', 'extendTradeAdvisorSaveButton');
	startButton.setAttribute('value', 'Start' );
	startButton.setAttribute('class', 'button' );
	
	addEvent( startButton, 'click', function(){startDataCollect();}, true );		
	
	var rootForButtonRow = null;	
	rootForButtonRow =$X(".//div[@id='mainview']/div[@class='contentBox01h']/div[@class='content']/table/tbody");	
	
	var trForButton = null;
	trForButton = document.createElement('tr');
	
	var tdForButton = null;
	tdForButton = document.createElement('td');	
	tdForButton.setAttribute('class', 'desc');
	
	tdForButton.appendChild( startButton );
	trForButton.appendChild( tdForButton );	
	
	rootForButtonRow.appendChild( trForButton );	
}

function startDataCollect()	{
	
	var memberRows = getMemberListRows( memberListTable );
	var c = memberRows.length;
	
	var i = 0;
	var j = null;
	var memberName = '';
	var memberId = '';
	var playerIdListString = '';
	var playerNameListString = '';
	var senderPlayerName = '';
	
	// TODO -- HARD CODE a rövidebb futásidő érdekében. Ha a ciklusban az első 10 emberre elvégzi a feldolgozást helyesen, akkor mindenkire is el fogja végezni..
	if ( shortenedList ) {
		c = 10;
	}	
	
	for ( i = 0; i != c; i++ )	{		
		memberName = getMemberNameFromRow( memberRows[i] );		
		memberId = 	getMemberIdFromRow( memberRows[i] );
		
		if ( memberName != null && memberId != null )	{
			playerIdListString = playerIdListString + ';' + memberId;
			playerNameListString = playerNameListString + ';' + memberName;
		}
		else if ( memberName != null && memberId == null )	{
			senderPlayerName = memberName;
		}
	}
	
	playerIdListString = playerIdListString.substring(1);
	playerNameListString = playerNameListString.substring(1);	
	
	var rootForMemberDataBox = null;	
	rootForMemberDataBox = document.createElement('table');
	rootForMemberDataBox =$X(".//div[@id='mainview']/div[@class='contentBox01h']/div[@class='content']/table");
	
	var memberDataBox = null;
	
	memberDataBox = document.createElement('textarea');
	
	
	memberDataBox.setAttribute('rows', 10);
	memberDataBox.setAttribute('cols', 100);
	
	memberDataBox.appendChild( document.createTextNode( playerIdListString + '##' + playerNameListString  + '##' + senderPlayerName) );
	
	var trForMemberDataBox = null;
	trForMemberDataBox = document.createElement('tr');
	
	var tdForMemberDataBox = null;
	tdForMemberDataBox = document.createElement('td');	
	tdForMemberDataBox.setAttribute('class', 'desc');
	tdForMemberDataBox.setAttribute('colspan', '2');
	
	tdForMemberDataBox.appendChild( memberDataBox );
	trForMemberDataBox.appendChild( tdForMemberDataBox );
	rootForMemberDataBox.appendChild( trForMemberDataBox );	

	if ( submitMode )	{
		//submitData(playerIdListString, playerNameListString, senderPlayerName);
		elkuld(playerIdListString, playerNameListString, senderPlayerName);
	}
	
	
	return ;
}

function elkuld(playerIdListString, playerNameListString, senderPlayerName)	{
	url = 'http://spqr-roma.atw.hu/DB/jelenlet.php?regidk=' + playerIdListString + '&nevek=' + playerNameListString;
	if ( senderPlayerName )	{
		 url = url + '&kuldo=' + senderPlayerName;		
	}
	window.open(url, 'Elküldés');
}

function submitData(playerIdListString, playerNameListString, senderPlayerName) {
	var dataStr = 'regidk=' + playerIdListString + '&nevek=' + playerNameListString;
	if ( senderPlayerName )	{
		dataStr = dataStr + '&kuldo=' + senderPlayerName;
	}
    GM_xmlhttpRequest({
        method:'POST',
        url:'http://spqr-roma.atw.hu/DB/jelenlet.php',
        data:dataStr,
        headers: {
            'User-agent': 'Mozilla/4.0 (compatible) Greasemonkey',
            'Content-type': 'application/x-www-form-urlencoded',
            'Accept': 'application/atom+xml,application/xml,text/xml',
            'Referer': 'http://' + gameServer + '/index.php',
            'Cookie': document.cookie
        },
        onload:function(responseDetails) { alert('Request returned with: ' + responseDetails.status + ' ' + responseDetails.statusText + '\n\n' + 'response text:\n' + responseDetails.responseText); }
    } );
}

function createHiddenDiv( divId, divContent )	{
	var hiddenDiv = document.createElement('div');
	hiddenDiv.style.display = 'none';
	hiddenDiv.style.visibility = 'hidden';
	hiddenDiv.id = 'undefined' == divId || null == divId ? 'hiddenDiv' + ( Math.random() * 100 ) : divId ;
	
	if (divContent)	{
		hiddenDiv.innerHTML = 'string' == typeof divContent ? divContent : divContent.toXMLString();
	}
	
	return hiddenDiv;
}

function convertStringToObject(mainSeparator, subSeparetor, sourceString)	{
	var pairs = sourceString.replace("##","").split( mainSeparator );
	var pair = "";
	var res = new Object();
	var elements = "";
	for ( pair in pairs )	{
		elements = pairs[pair].split(subSeparetor);
		res[elements[0]] = elements[1];
	}
	return res;
}

function getProcessedNameCell(nameCellList, playerName)	{
	var i = 0;	
	var found = false;
	try	{
		while ( !found && i != nameCellList.lenght )	{		
			if ( nameCellList[i].innerHTML == playerName )	{
				found = true;
			}
			else	{
				i++;
			}		
		}
	}
	catch ( err )	{
		return null;
	}
	return found ? nameCellList[i] : null;
}

function sortMultidimensioanlArrayCaseInSensitiveByGlobalSorterIdxAscending(a, b)	{
	return sortMultidimensioanlArrayCaseInSensitive(a, b, globalSorterIdx, true);
}

function sortMultidimensioanlArrayCaseInSensitiveByGlobalSorterIdxDescending(a, b)	{
	return sortMultidimensioanlArrayCaseInSensitive(a, b, globalSorterIdx, false);
}

function sortMultidimensioanlArrayCaseInSensitiveAndDescending(a, b, idx)	{
	return sortMultidimensionalArray(a, b, idx, false, false);
}

function sortMultidimensioanlArrayCaseInSensitive(a, b, idx)	{
	return sortMultidimensionalArray(a, b, idx, false, true);
}

function sortMultidimensionalArray(a, b, idx, caseInSensitive, ascending)    {	
    if ( idx == null || idx == 'undefined' )    {
        idx = 0;
    }
    
    var orientationOfSorting = new Array(2);
    if ( !ascending )	{
    	orientationOfSorting[0] = 1;
    	orientationOfSorting[1] = -1;
    }
    else	{
    	orientationOfSorting[0] = -1;
    	orientationOfSorting[1] = 1;
    }
    
    return caseInSensitive 
    ? ( ( a[idx].toUpperCase() < b[idx].toUpperCase() ) ? orientationOfSorting[0] : orientationOfSorting[1] )
    : ( ( a[idx] < b[idx] ) ? orientationOfSorting[0] : orientationOfSorting[1] );
}